<template>
	<view class="container">
		<view class="flex">
			<view class="red-text">*</view>
			<view class="blod-text">标题</view>
		</view>
		<view class="input-box mt-30">
			<uv-input placeholder="输入活动标题(最多15字)" border="bottom" maxlength="15" v-model="title"></uv-input>
		</view>
		<view class="flex mt-30">
			<view class="red-text">*</view>
			<view class="blod-text">内容</view>
		</view>
		<view class="text-area mt-30">
			<uv-textarea v-model="content" border="bottom" placeholder="请输入活动内容" count maxlength="400"></uv-textarea>
		</view>
		<view class="flex mt-30">
			<view class="red-text">*</view>
			<view class="blod-text">地点</view>
		</view>
		<view class="input-box mt-30">
			<uv-input placeholder="活动地点(最多25字)" border="bottom" maxlength="25" v-model="location"></uv-input>
		</view>
		<view class="flex mt-30">
			<view class="red-text">*</view>
			<view class="blod-text">主办方机构</view>
		</view>
		<view class="input-box mt-30">
			<uv-input placeholder="主办方机构(最多25字)" border="bottom" maxlength="25" v-model="name"></uv-input>
		</view>
		<view class="mt-30 flex">
			<view class="red-text">*</view>
			<view class="a-center">活动时间：</view>
			<uv-datetime-picker ref="datetimePicker" title="请选择活动时间" v-model="dateStamp" mode="datetime" @confirm="confirm"
				:maxDate="Date.now() + 31536000000" :minDate="Date.now()">
			</uv-datetime-picker>
			<view class="select-text" @click="open">{{activity_date || '请选择日期'}}</view>
		</view>
		<view class="mt-30 flex">
			<view class="red-text">*</view>
			<view class="a-center">报名截止时间：</view>
			<uv-datetime-picker ref="datetimePicker2" title="请选择报名截止时间" v-model="dateStampP" mode="datetime" @confirm="confirmP"
				:maxDate="Date.now() + 31536000000" :minDate="Date.now()">
			</uv-datetime-picker>
			<view class="select-text" @click="openP">{{close_date || '请选择日期'}}</view>
		</view>
		<view class="mt-30 flex">
			<view class="red-text">*</view>
			<view class="a-center">活动类型：</view>
			<view class="select-text" @click="this.$refs.picker.open();">{{selectedType}}</view>
			<uv-picker ref="picker" :columns="columns" title="请选择活动类型" @confirm="confirmType"></uv-picker>
		</view>
		<view class="mt-50">
			<view class="blod-text">上传图片(至少选择一张且第一张为封面)</view>
			<view class="mt-50">
				<uv-upload :fileList="fileList1" name="1" :deletable='true' :multiple='false' :maxCount="3"
					@afterRead="afterRead" @delete="deletePic"></uv-upload>
			</view>
		</view>
		<view class="mt-50">
			<uv-button type="primary" text="确定发布" @click="publishContent"></uv-button>
		</view>
	</view>
	<uv-toast ref="toast"></uv-toast>
</template>

<script>
	import {
		formatDateTime,
		filterSensitiveWords
	} from '../../../utils/utils.js'
	export default {
		data() {
			return {
				title: '', // 标题内容
				content: '', // 文本内容
				fileList1: [], //上传的图片临时路径
				img_list: [], // 云端图片路径
				location: '', // 地点
				activity_date: '', // 活动时间
				dateStamp: '', // 活动时间时间戳
				close_date: '', // 报名截止时间
				dateStampP: '', // 报名截止时间时间戳
				name: '', // 主办方机构名称
				columns: [['校内活动', '校外活动']] ,// 活动类型
				selectedType:'请选择活动类型', // 选择的活动类型
			}
		},
		methods: {
			formatDateTime,
			filterSensitiveWords,
			openPicker() {
				this.$refs.picker.open();
			},
			// 选择时间
			open() {
				this.$refs.datetimePicker.open()
			},
			confirm(e) {
				this.activity_date = formatDateTime(e.value)
				this.dateStamp = +e.value
			},
			openP() {
				this.$refs.datetimePicker2.open()
			},
			confirmP(e) {
				this.close_date = formatDateTime(e.value)
				this.dateStampP = +e.value
			},
			openType(e){
				this.$refs.picker.open();
			},
			confirmType(e) {
				this.selectedType = e.value[0]
			},
			// 以下为图片上传
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				const user_info = uni.getStorageSync('user_info')
				console.log('lists', lists)
				for (let i = 0; i < lists.length; i++) {
					const list = {
						pathName: `images/schoolArticles/${user_info.user_name}/${Date.now()}.jpg`,
						path: lists[i].url
					}
					try {
						const result = await this.uploadFilePromise(list)
						console.log('Upload result:', result) // 添加日志
						if (result.fileID) {
							this.img_list.push(result.fileID)
							let item = this[`fileList${event.name}`][fileListLen]
							this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
								status: 'success',
								message: '',
								url: result.fileID
							}))
							fileListLen++
						} else {
							console.error('Upload failed: No fileID returned')
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							})
						}
					} catch (error) {
						console.error('Upload error:', error)
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						})
					}
				}
			},
			uploadFilePromise(item) {
				return new Promise((resolve, reject) => {
					uniCloud.uploadFile({
						cloudPathAsRealPath: true,
						filePath: item.path,
						cloudPath: item.pathName,
						success: (res) => {
							console.log('Upload success:', res)
							resolve(res)
						},
						fail: (err) => {
							console.error('Upload fail:', err)
							reject(err)
						}
					})
				})
			},
			// 内容发布
			async publishContent() {
				if (!this.title) {
					const mess = filterSensitiveWords(this.content)
					if (mess) {
						this.$refs.toast.show({
							type: 'warning',
							message: `检测到敏感词${mess[0]}，请检查内容后再尝试发布`
						});
						return
					}
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入标题"
					});
					return
				} else if (!this.content) {
					const mess = filterSensitiveWords(this.content)
					if (mess) {
						this.$refs.toast.show({
							type: 'warning',
							message: `检测到敏感词${mess[0]}，请检查内容后再尝试发布`
						});
						return
					}
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入内容"
					});
					return
				} else if (!this.location) {
					const mess = filterSensitiveWords(this.content)
					if (mess) {
						this.$refs.toast.show({
							type: 'warning',
							message: `检测到敏感词${mess[0]}，请检查内容后再尝试发布`
						});
						return
					}
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入地点"
					});
					return
				} else if (!this.name) {
					const mess = filterSensitiveWords(this.content)
					if (mess) {
						this.$refs.toast.show({
							type: 'warning',
							message: `检测到敏感词${mess[0]}，请检查内容后再尝试发布`
						});
						return
					}
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入主办方机构"
					});
					return
				} else if (!this.activity_date) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请选择活动时间"
					});
					return
				} else if (!this.close_date) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请选择报名截止时间"
					});
					return
				}else if (this.selectedType === '请选择活动类型') {
					this.$refs.toast.show({
						type: 'warning',
						message: "请选择活动类型"
					});
					return
				}
				const user_info = uni.getStorageSync('user_info')
				try {
					const db = uniCloud.database();
					const collection = db.collection('schoolActivity')
					const res = await collection.add({
						title: this.title,
						content: this.content,
						place: this.location,
						activity_timeStr: this.activity_date,
						activity_time:this.dateStamp,
						close_time:this.dateStampP,
						close_timeStr: this.close_date,
						img_list: this.img_list,
						user_name: user_info.user_name,
						user_img:user_info.user_img,
						user_id: user_info._id,
						name: this.name,
						type:this.selectedType,
						createTime:Date.now(),
						number_likes: 0,
						user_likes_list: [],
						number_collection:0,
						user_collection_list:[],
						number_comments:0,
						join_list:[],
					})
					if (res) {
						this.$refs.toast.show({
							type: "success",
							message: "发布成功！"
						})
						// 清空表单
						this.title = ''
						this.content = ''
						this.img_list = []
						this.fileList1 = []
						this.location = ''
						this.name = ''
						this.activity_date = ''
						this.close_date = ''
						// 返回上一页
						uni.navigateBack()
					} else {
						this.$refs.toast.show({
							type: "error",
							message: res.result.errMsg || "发布失败，请重试"
						})
					}
				} catch (e) {
					console.error('发布文章时发生错误:', e)
					this.$refs.toast.show({
						type: "error",
						message: "发布失败，请重试"
					})
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 30rpx;
	}

	.more-box {
		padding: 30rpx;
		background-color: #ebebeb;
	}

	.select-text {
		color: rgb(118, 122, 130);
		font-weight: 400;
	}
</style>